//
//  EdHeadViewController.m
//  RENTVISITOR
//
//  Created by wonder on 2017/9/28.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "EdHeadViewController.h"
#import "RentVieitor.h"

@interface EdHeadViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIGestureRecognizerDelegate>

@end

@implementation EdHeadViewController {
    
    UIImageView *photoView;
    UIImageView *editView;
    UIImage *editImg;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = BackgroundColor;
    [self creatLeftView];
    [self creatView];
}

- (void)creatLeftView {
    
    // 自定义导航栏左侧按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 10,15 );
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"箭头左"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    // 自定义导航栏左侧按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.frame = CGRectMake(0, 0, 50, 20);
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor colorWithRed:99/255.0 green:99/255.0 blue:99/255.0 alpha:1] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
}

- (void)creatView {
    
    photoView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    photoView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:photoView];
    
    //500 375
    
    editView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KWidth*375/500, KWidth*375/500)];
    CGPoint point = CGPointMake(self.view.center.x, self.view.center.y-64);
    editView.center = point;
    editView.userInteractionEnabled =YES;
    editView.backgroundColor = [UIColor whiteColor];
    editView.alpha = 0.8;
    [self.view insertSubview:editView aboveSubview:photoView];
    
    //添加手势
    UITapGestureRecognizer * PrivateLetterTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarView)];
    PrivateLetterTap.numberOfTouchesRequired = 1; //手指数
    PrivateLetterTap.numberOfTapsRequired = 1; //tap次数
    [editView addGestureRecognizer:PrivateLetterTap];
    
    //平移手势添加
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGRAct:)];
    panGestureRecognizer.delegate = self;
    //    panGestureRecognizer.minimumNumberOfTouches = 2;
    [editView addGestureRecognizer:panGestureRecognizer];
    
}

- (void)panGRAct: (UIPanGestureRecognizer *)rec{
    
    
    CGPoint point = [rec translationInView:self.view];
    NSLog(@"%f,%f",point.x,point.y);
    rec.view.center = CGPointMake(rec.view.center.x + point.x, rec.view.center.y + point.y);
    [rec setTranslation:CGPointMake(0, 0) inView:self.view];
}


- (void)tapAvatarView{
    
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            // 跳转到相机页面
            UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self;
            //            imagePickerController.allowsEditing = NO;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            [self.navigationController presentViewController:imagePickerController animated:YES completion:NULL];
        }
        
        
        
    }];
    
    
    UIAlertAction *picAlbumAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //跳转到相册
        UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //pickerImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
            
        }
        pickerImage.delegate = self;
        pickerImage.allowsEditing = NO;
        //        [self presentModalViewController:pickerImage animated:YES];
        [self.navigationController presentViewController:pickerImage animated:YES completion:NULL];
        
        
    }];
    
    UIAlertAction *canceAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertVC addAction:photoAction];
    [alertVC addAction:picAlbumAction];
    [alertVC addAction:canceAction];
    [self presentViewController:alertVC animated:YES completion:NULL];
    
}

#pragma mark -- 成功获得相片还是视频后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    //通过UIImagePickerControllerMediaType判断返回的是照片还是视频
    NSString* type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //如果返回的type等于kUTTypeImage，代表返回的是照片,并且需要判断当前相机使用的sourcetype是拍照还是相册
    if ([type isEqualToString:(NSString*)kUTTypeImage]) {
        
        //获取照片的原图
        UIImage *original = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        //将图片大小压缩
        //        UIImage *samllImg = [self scaleImage:original toKb:400];
        UIImage *samllImg = [self imageCompressForWidthScale:original targetWidth:500];
        CGSize size = samllImg.size;
        CGFloat scale = KWidth/size.width;
        photoView.frame = CGRectMake(0, 0, size.width*scale, size.height*scale);
        CGPoint point = CGPointMake(self.view.center.x, self.view.center.y-64);
        photoView.center = point;
        photoView.image = samllImg;
        editImg = samllImg;
        
        //NSData * imageData2 = UIImageJPEGRepresentation(samllImg,0.9f);
        //long length2 = [imageData2 length]/1024.0f;
        // NSLog(@"压缩后大小%ldKB",length2);
        
        
        
        
        //        //如果是拍照的照片，则需要手动保存到本地，系统不会自动保存拍照成功后的照片
        //        UIImageWriteToSavedPhotosAlbum(samllImg, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        
        //        NSURL *picurl=[info objectForKey:UIImagePickerControllerReferenceURL];
    }
    //模态方式退出uiimagepickercontroller
    [picker dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark 图片压缩
-(UIImage *) imageCompressForWidthScale:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
    
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height / (width / targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        
        NSLog(@"scale image fail");
    }
    UIGraphicsEndImageContext();
    return newImage;
}




- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

//获得某个范围内的屏幕图像
- (UIImage *)ct_imageFromImage:(UIImage *)image inRect:(CGRect)rect{
    
    CGRect dianRect = CGRectMake(rect.origin.x,rect.origin. y,rect.size.width, rect.size.height);
    
    //截取部分图片并生成新图片
    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, dianRect);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef scale:1 orientation:UIImageOrientationUp];
    return newImage;
}

- (void)saveAction {
    
//    CGPoint *point = [editView. convertRect: toView:view_B];
//    UIImage *img = [self ct_imageFromImage:editImg inRect:;
//    editView.image = img;
}
                    
                    
@end
